import 'package:meta/meta.dart';

import '../cache.dart';
import 'base_store.dart';

/// A [CacheStore] that keeps all its values in memory.
class MemoryCacheStore<T> extends BaseCacheStore<T> {

  @protected
  final List<Cache<T>> items = [];

  @override
  Future<void> clean(CachePriority priority) {
    items.removeWhere((x) => x.priority.index < priority.index);
    return Future.value();
  }

  @override
  Future<Cache<T>> read(String key) {
    return Future.value(items.firstWhere((x) => x.key == key, orElse:() => null));
  }

  @override
  Future<List<Cache<T>>> readAll(List<String> keys) {
    return Future.value(items.where((x) => keys.contains(x.key)).toList());
  }

  @override
  Future<void> set(Cache<T> value) {
    items.removeWhere((x) => x.key == value.key);
    items.insert(0,value);
    return Future.value();
  }

  @override
  Future<void> setAll(List<Cache<T>> values) {
    items.removeWhere((x) => values.any((v) => x.key == v.key));
    items.insertAll(0,values);
    return Future.value();
  }

  @override
  Future<void> delete(String key) {
    items.removeWhere((x) => x.key == key);
    return Future.value();
  }
}
